package com.zlx.sharelive.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;
import android.renderscript.Allocation;
import android.renderscript.Element;
import android.renderscript.RenderScript;
import android.renderscript.ScriptIntrinsicBlur;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;

import com.zlx.module_base.base_ac.BaseAc;
import com.zlx.module_base.base_api.res_data.QueryByBean;
import com.zlx.module_base.base_api.util.ApiUtil;
import com.zlx.module_base.base_fg.BaseFg;
import com.zlx.module_base.base_util.SPUtil;
import com.zlx.module_network.api1.livedata.BaseObserver;
import com.zlx.module_network.api1.livedata.BaseObserverCallBack;
import com.zlx.module_network.bean.ApiResponse;
import com.zlx.sharelive.Constants;
import com.zlx.sharelive.R;
import com.zlx.sharelive.fragment.MyArticleFg2;
import com.zlx.sharelive.fragment.MyGraphicFg2;
import com.zlx.sharelive.fragment.MyLongVideoFg2;
import com.zlx.sharelive.fragment.MyShortVideoFg2;
import com.zlx.sharelive.utils.GlideImgManager;
import com.zlx.sharelive.utils.StringUt;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 个人主页
 */
public class HomepageAc extends BaseAc {

    @BindView(R.id.iv_head)
    ImageView iv_head;
    @BindView(R.id.tv_nickname)
    TextView tv_nickname;
    @BindView(R.id.tv_id)
    TextView tv_id;
    @BindView(R.id.tv_make)
    TextView tv_make;
    @BindView(R.id.tv_content)
    TextView tv_content;
    @BindView(R.id.tv_praise)
    TextView tv_praise;
    @BindView(R.id.tv_attention)
    TextView tv_attention;
    @BindView(R.id.tv_fan)
    TextView tv_fan;
    @BindView(R.id.tv_type1)
    TextView tv_type1;
    @BindView(R.id.tv_type2)
    TextView tv_type2;
    @BindView(R.id.tv_type3)
    TextView tv_type3;
    @BindView(R.id.tv_type4)
    TextView tv_type4;
    @BindView(R.id.view_type1)
    View view_type1;
    @BindView(R.id.view_type2)
    View view_type2;
    @BindView(R.id.view_type3)
    View view_type3;
    @BindView(R.id.view_type4)
    View view_type4;
    @BindView(R.id.tv_pay_close_attention)
    TextView tv_pay_close_attention;
    @BindView(R.id.iv_head_bg)
    ImageView iv_head_bg;

    private List<TextView> mTextViewList = new ArrayList<>();
    private List<View> mViewList = new ArrayList<>();
    private List<BaseFg> mFragment = new ArrayList<>();
    private QueryByBean.InfoDTO.ResultDTO mData;

    @Override
    protected int getLayoutId() {
        return R.layout.ac_homepage;
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    iv_head_bg.setImageBitmap((Bitmap) msg.obj);
                    break;
            }
        }
    };

    @Override
    public void initViews() {
        super.initViews();

        tv_pay_close_attention.setVisibility(View.GONE);
        mTextViewList.clear();
        mTextViewList.add(tv_type1);
        mTextViewList.add(tv_type2);
        mTextViewList.add(tv_type3);
        mTextViewList.add(tv_type4);
        mViewList.clear();
        mViewList.add(view_type1);
        mViewList.add(view_type2);
        mViewList.add(view_type3);
        mViewList.add(view_type4);

        queryById();
        initFragment();
    }

    private void initFragment() {
        mFragment.clear();
        mFragment.add(new MyLongVideoFg2());
        mFragment.add(new MyShortVideoFg2());
        mFragment.add(new MyArticleFg2());
        mFragment.add(new MyGraphicFg2());
        commitAllowingStateLoss(0);
    }

    private void commitAllowingStateLoss(int position) {
        hideAllFragment();
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        Fragment currentFragment = getSupportFragmentManager().findFragmentByTag(position + "");
        if (currentFragment != null) {
            transaction.show(currentFragment);
        } else {
            currentFragment = mFragment.get(position);
            transaction.add(R.id.fl_layout, currentFragment, position + "");
        }
        transaction.commitAllowingStateLoss();
    }

    /**
     * 隐藏所有Fragment
     */
    private void hideAllFragment() {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        for (int i = 0; i < mFragment.size(); i++) {
            Fragment currentFragment = getSupportFragmentManager().findFragmentByTag(i + "");
            if (currentFragment != null) {
                transaction.hide(currentFragment);
            }
        }
        transaction.commitAllowingStateLoss();
    }

    private void queryById() {
        ApiUtil.getLoginApi().queryById(SPUtil.getToken(this),(String) SPUtil.get(this, Constants.SP_ID, ""))
                .observe(this, new BaseObserver<>(new BaseObserverCallBack<ApiResponse<QueryByBean>>() {
                    @Override
                    public void onSuccess(ApiResponse<QueryByBean> data) {
                        if (null != data) {
                            if (null != data.getData()) {
                                if (data.getData().getCode() == 0) {
                                    if (null != data.getData().getInfo()) {
                                        if (data.getData().getInfo().size() > 0) {
                                            if (null != data.getData().getInfo().get(0).getResult()) {
                                                mData = data.getData().getInfo().get(0).getResult();
                                                setData(mData);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();

                    }
                }));
    }

    private void setData(QueryByBean.InfoDTO.ResultDTO mData) {
        GlideImgManager.glideLoader(this, mData.getAvatar(), iv_head, 0);
        tv_nickname.setText(mData.getNickname());
        tv_id.setText("ID:" + mData.getId());
        if (!StringUt.isEmpty(mData.getMakingType())) {
            tv_make.setText("交友的属性:" + mData.getMakingType());
        } else {
            tv_make.setText("交友的属性:未知");
        }
        tv_content.setText(mData.getSignature());
        tv_praise.setText(mData.getLike());
        tv_attention.setText(mData.getFocusedCount());
        tv_fan.setText(mData.getFansCount());
        new Thread() {
            @Override
            public void run() {
                super.run();
                Bitmap bitmap = getBitMBitmap(mData.getAvatar());
                Bitmap bitmap1 = blurBitmap(bitmap, HomepageAc.this);
                Bitmap bitmap2 = blurBitmap(bitmap1, HomepageAc.this);
                Bitmap bitmap3 = blurBitmap(bitmap2, HomepageAc.this);
                Message msg = new Message();
                msg.what = 1;
                msg.obj = bitmap3;
                handler.sendMessage(msg);
            }
        }.start();


    }

    @OnClick({R.id.iv_back,R.id.ll_type1, R.id.ll_type2, R.id.ll_type3, R.id.ll_type4,
            R.id.ll_layout1, R.id.ll_layout2, R.id.ll_layout3})
    public void setOnClick(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.ll_type1:
                commitAllowingStateLoss(0);
                setTextColor(0);
                break;
            case R.id.ll_type2:
                commitAllowingStateLoss(1);
                setTextColor(1);
                break;
            case R.id.ll_type3:
                commitAllowingStateLoss(2);
                setTextColor(2);
                break;
            case R.id.ll_type4:
                commitAllowingStateLoss(3);
                setTextColor(3);
                break;
            case R.id.ll_layout1:
                startActivity(new Intent(this, MyLikeAc.class));
                break;
            case R.id.ll_layout2:
                startActivity(new Intent(this, MyFollowAc.class));
                break;
            case R.id.ll_layout3:
                startActivity(new Intent(this, MyFansAc.class));
                break;
        }
    }

    public void setTextColor(int position) {
        for (int i = 0; i < mTextViewList.size(); i++) {
            if (position == i) {
                mTextViewList.get(position).setTextColor(getResources().getColor(R.color.hot_pink));
                mViewList.get(position).setVisibility(View.VISIBLE);
            } else {
                mTextViewList.get(i).setTextColor(getResources().getColor(R.color.black));
                mViewList.get(i).setVisibility(View.INVISIBLE);
            }
        }
    }

    public static Bitmap getBitMBitmap(String urlpath) {
        Bitmap map = null;
        try {
            URL url = new URL(urlpath);
            URLConnection conn = url.openConnection();
            conn.connect();
            InputStream in;
            in = conn.getInputStream();
            map = BitmapFactory.decodeStream(in);
            // TODO Auto-generated catch block
        } catch (IOException e) {
            e.printStackTrace();
        }
        return map;
    }

    public static Bitmap blurBitmap(Bitmap bitmap, Context context) {

        //Let's create an empty bitmap with the same size of the bitmap we want to blur
        Bitmap outBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);

        //Instantiate a new Renderscript
        RenderScript rs = RenderScript.create(context);

        //Create an Intrinsic Blur Script using the Renderscript
        ScriptIntrinsicBlur blurScript = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));

        //Create the Allocations (in/out) with the Renderscript and the in/out bitmaps
        Allocation allIn = Allocation.createFromBitmap(rs, bitmap);
        Allocation allOut = Allocation.createFromBitmap(rs, outBitmap);

        //Set the radius of the blur: 0 < radius <= 25
        blurScript.setRadius(25.0f);

        //Perform the Renderscript
        blurScript.setInput(allIn);
        blurScript.forEach(allOut);

        //Copy the final bitmap created by the out Allocation to the outBitmap
        allOut.copyTo(outBitmap);

        //recycle the original bitmap
        bitmap.recycle();

        //After finishing everything, we destroy the Renderscript.
        rs.destroy();

        return outBitmap;
    }
}
